import 'package:base_moudle/index.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../../api/api.dart';
import '../../../config/zs_routers.dart';
import '../../../new_paltform/commonwidgets/hy_date_picker.dart';
import '../../../new_paltform/define/hy_event_bus.dart';
import '../../../new_paltform/define/hy_header.dart';
import '../../command/project/zs_project_introduce/zs_project_introduce_logic.dart';
import '../../other/speech_search/voice_search_manager.dart';
import 'hy_work_home_logic.dart';
import 'hy_workbench_detail_view.dart';
import 'my_work/hy_me_work_logic.dart';
import 'my_work/hy_me_work_page.dart';
import 'project/hy_work_project_detail_logic.dart';

class HyWorkHomePage extends StatefulWidget {
  @override
  _HyWorkHomePageState createState() => _HyWorkHomePageState();
}

class _HyWorkHomePageState extends State<HyWorkHomePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin, NetworkMixin {
  final ZsProjectIntroduceLogic logic =
      Get.put(ZsProjectIntroduceLogic(), tag: 'newHome');

  HyWorkHomeLogic controller = Get.put(HyWorkHomeLogic());

  final HyWorkProjectDetailLogic logic1 = Get.put(HyWorkProjectDetailLogic());
  var eventBusFn;
  SearchManager? manager;
  late TabController tabController;
  List<TabbarItem> tabs = [];
  final List<TabbarItem> constTabs = [
    TabbarItem(page: HYMeWorkDetailPage(), title: '个人项目'),
    TabbarItem(page: HYWorkbenchDetailPage(), title: '工作台')
  ];
  String? juid;
  String? juid1;
  String? juid2;

  RxBool projectSwitch = false.obs;
  RxBool openSwitch = false.obs;

  @override
  void initState() {
    super.initState();
    // 注册监听器，订阅 eventbus
    eventBusFn = eventBus.on<HYEvent>().listen((HYEvent event) async {
      if (event.type == HYEventType.refreshPage) {
        controller.companyName.value = '';
        controller.requestProjectDetail();
        initTabs();
        setState(() {});
      } else if (event.type == HYEventType.appHomeWorkAppNotification) {
        initTabs();
        setState(() {});
      }
    });
    controller.callback = (arg) {
      manager = SearchManager(arg: arg)..init();
    };
    controller.requestProjectDetail();
    initTabs();
  }

  Future<void> initTabs() async {
    juid = ZsMemeryCache.loginDataModel?.userInfo?.juid;
    juid1 = ZsMemeryCache.loginDataModel?.userInfo?.juid1;
    juid2 = ZsMemeryCache.loginDataModel?.userInfo?.juid2;
    final String? workPath = ZsMemeryCache.zsWorkLoginModel?.workPath;
    if (workPath.isNullOrEmpty()) {
      final ZsWorkLoginModel zsWorkLoginModel =
          ZsWorkLoginModel('', '', '', '', '', '', '');
      ZsMemeryCache.pullToWorkCache(zsWorkLoginModel);
      if (juid.isNotNullOrEmpty()) {
        ZsMemeryCache.zsWorkLoginModel?.workPath = WorkPath_YM;
        ZsMemeryCache.zsWorkLoginModel?.workModuleUserId = juid;
      } else if (juid2.isNotNullOrEmpty()) {
        ZsMemeryCache.zsWorkLoginModel?.workPath = WorkPath_SP;
        ZsMemeryCache.zsWorkLoginModel?.workModuleUserId = juid2;
      } else if (juid1.isNotNullOrEmpty()) {
        ZsMemeryCache.zsWorkLoginModel?.workPath = WorkPath_XB;
        ZsMemeryCache.zsWorkLoginModel?.workModuleUserId = juid1;
      }
    }
    if (ZsMemeryCache.isMeWork) {
      tabs = constTabs.where((element) => element.title == '个人项目').toList();
      controller.pageStatus.value = PageStatus.normal;
      controller.companyName.value = '个人项目';
    } else {
      tabs = constTabs.where((element) => element.title == '工作台').toList();
      if(juid2.isNullOrEmpty() && juid.isNullOrEmpty()){
        controller.companyName.value = '工作台';
      }
    }

    final bool isMiniShow =
        ZsMemeryCache.loginDataModel?.userInfo?.isMiniShow ?? false;
    if (isMiniShow && (juid.isNotNullOrEmpty() || juid2.isNotNullOrEmpty()) ||
        (juid.isNotNullOrEmpty() && juid2.isNotNullOrEmpty())) {
      projectSwitch.value = true;
    } else {
      projectSwitch.value = false;
    }

    tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  void dispose() {
    Get.delete<ZsProjectIntroduceLogic>(tag: 'newHome');
    super.dispose();
    //取消订阅
    eventBusFn.cancel();
  }

  ///用户信息
  Widget _buildUserView(BuildContext context) {
    String userHeader = '';
    if (ZsMemeryCache.loginDataModel?.userInfo?.userHeaderImg != null) {
      if (ZsMemeryCache.loginDataModel?.userInfo?.userHeaderImg!
              .toString()
              .contains('http') ==
          false) {
        userHeader = OBSPath.toString() +
            (ZsMemeryCache.loginDataModel?.userInfo?.userHeaderImg as String);
      } else {
        userHeader =
            ZsMemeryCache.loginDataModel?.userInfo?.userHeaderImg as String;
      }
    }
    return Expanded(
      child: HYContainer(
        key: controller.keyGreen,
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            CircleAvatar(
              radius: 23,
              backgroundColor: zs_color_f9,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20),
                child: userHeader == ''
                    ? Image.asset(
                        'assets/images/project/avtar.png',
                        width: 40,
                        height: 40,
                        fit: BoxFit.cover,
                      )
                    : CachedNetworkImage(
                        imageUrl: userHeader,
                        width: 40,
                        height: 40,
                        fit: BoxFit.cover,
                        errorWidget: (BuildContext ctx, String t, d) {
                          return Image.asset('assets/images/project/avtar.png');
                        },
                      ),
              ),
            ).marginOnly(right: 8),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    ZsText(
                      '${ZsMemeryCache.loginDataModel?.userInfo?.nickName ?? ''}',
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                    ),
                    Obx(() {
                      if (projectSwitch.value) {
                        return Image.asset(
                          openSwitch.value
                              ? 'assets/images/project/work_selected.png'
                              : 'assets/images/project/work_unchecked.png',
                          width: 8,
                          height: 8,
                        ).marginOnly(bottom: 3, left: 5);
                      } else {
                        return Container();
                      }
                    }),
                  ],
                ),
                Obx(() => ZsText(
                      controller.companyName.value,
                      fontSize: 12,
                      maxLines: 1,
                    ))
              ],
            )),
          ],
        ),
        onTap: () {
          final bool isJuids =
              ZsMemeryCache.loginDataModel?.userInfo?.isJuids ?? false;
          final bool isMiniShow =
              ZsMemeryCache.loginDataModel?.userInfo?.isMiniShow ?? false;
          if (!isJuids && !isMiniShow) {
            return;
          }
          final bool isProjectShow =
              ZsMemeryCache.loginDataModel?.userInfo?.isProjectShow ?? false;
          final bool isMe = ZsMemeryCache.isMeWork;
          final bool isMore =
              juid.isNotNullOrEmpty() && juid2.isNotNullOrEmpty();


          openSwitch.value = true;
          HYDatePicker.showFilterDialogPage(
                  context,
                  HYContainer(
                    width: Get.width,
                    // alignment: Alignment.topCenter,
                    padding: const EdgeInsets.only(top: 10, bottom: 16),
                    backgroundColor: Colors.white,
                    borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(10),
                        bottomRight: Radius.circular(10)),
                    child: Column(
                      children: [
                        if (isJuids)
                          _buildSelectedCell(
                              name: '切换公司',
                              icon:
                                  'assets/images/project/work_selecte_company.png',
                              row: 0,
                              isStore: isMore,
                              isSelect: !isMe),
                        if (!isJuids && isProjectShow)
                          _buildSelectedCell(
                              name: '切换工作台',
                              icon:
                                  'assets/images/project/work_selecte_company.png',
                              row: 2,
                              isSelect: !isMe),
                        if (isMiniShow)
                          _buildSelectedCell(
                              name: '切换个人工作台',
                              icon: 'assets/images/project/work_me_manage.png',
                              row: 1,
                              isSelect: isMe),
                      ],
                    ),
                  ),
                  controller.keyGreen)
              .whenComplete(() => openSwitch.value = false);
        },
      ),
    );
  }

  Widget _buildSelectedCell(
      {required String name,
      required String icon,
      required int row,
      bool isStore = false,
      bool isSelect = true}) {
    return Card(
      margin: const EdgeInsets.all(8),
      color: isSelect ? ColorHex('#F2F2F2') : Colors.white,
      shadowColor: Colors.transparent,
      child: HYContainer(
        onTap: () {
          Get.back();
          if (row == 1) {
            if (!ZsMemeryCache.isMeWork) {
              ZsMemeryCache.saveMeWrokType(true);
              eventBus
                  .fire(HYEvent(type: HYEventType.appHomeWorkAppNotification));
            }
            if (Get.isRegistered<HyMeWorkHomeLogic>()) {
              HyMeWorkHomeLogic _logic = Get.find();
              _logic.onAllData();
            }
          } else {
            if (ZsMemeryCache.isMeWork) {
              ZsMemeryCache.saveMeWrokType(false);
              eventBus
                  .fire(HYEvent(type: HYEventType.appHomeWorkAppNotification));
            } else {
              if (juid.isNotNullOrEmpty() && juid2.isNotNullOrEmpty()) {
                if (ZsMemeryCache.zsWorkLoginModel?.workPath == WorkPath_YM) {
                  ZsMemeryCache.zsWorkLoginModel?.workPath = WorkPath_SP;
                  ZsMemeryCache.zsWorkLoginModel?.workModuleUserId = juid2;
                } else {
                  ZsMemeryCache.zsWorkLoginModel?.workPath = WorkPath_YM;
                  ZsMemeryCache.zsWorkLoginModel?.workModuleUserId = juid;
                }
                controller.workStatus.value = PageStatus.loading;
                controller.loginWork();
              }
            }
          }
        },
        padding: const EdgeInsets.fromLTRB(8, 12, 20, 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Image.asset(icon, width: 30, height: 30),
                ZsText(name, fontWeight: FontWeight.bold, left: 12),
              ],
            ),
            if (isSelect)
              Image.asset(
                'assets/images/project/work_check.png',
                width: 18,
              )
            else
              !isStore
                  ? Image.asset(
                      'assets/images/project/work_arrows.png',
                      width: 18,
                    )
                  : Container()
          ],
        ),
      ),
    );
  }

  Widget _buildSearchBar(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildUserView(context),
        Image.asset(
          'assets/images/project/voiceSearch.png',
          width: 28,
          height: 28,
        )
            .intoContainer(padding: const EdgeInsets.only(left: 5))
            .intoGestureDetector(onTap: () async {
          if (ZsMemeryCache.loginDataModel?.userInfo?.userId == null) {
            await ZsMemeryCache.removeUserInfo();
            Get.toNamed(ZsRouter.zsPhoneLoginRouter);
          } else {
            if (manager != null) {
              manager!.showVoiceSearch();
              setState(() {});
            }
          }
        }),
        Image.asset(
          'assets/images/homeIcons/home_search.png',
          width: 28,
          height: 28,
        )
            .intoContainer(padding: const EdgeInsets.only(left: 20))
            .intoGestureDetector(onTap: () async {
          if (ZsMemeryCache.loginDataModel?.userInfo?.userId == null) {
            await ZsMemeryCache.removeUserInfo();
            Get.toNamed(ZsRouter.zsPhoneLoginRouter);
          } else {
            Get.toNamed(ZsRouter.ZsWorkSearchPageRouter);
          }
        }),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget floatingButton = Container();
    if (juid.isNotNullOrEmpty() || juid2.isNotNullOrEmpty()) {
      floatingButton = FloatingActionButton.extended(
        onPressed: () {
          clockIn();
        },
        icon: const Icon(Icons.location_on_rounded),
        label: const Text('立即打卡'),
      );
    }

    return Stack(children: [
      Obx(() => PageViewBase(
            status: controller.pageStatus.value,
            floatingActionButton: floatingButton,
            appBar: AppBar(
                backgroundColor: Colors.transparent,
                shadowColor: Colors.transparent,
                leading: Container(),
                leadingWidth: 0,
                title: HYContainer(
                  // width: Get.width - 40,
                  child: _buildSearchBar(context),
                ),
                bottom: tabs.length > 1
                    ? PreferredSize(
                        preferredSize: const Size.fromHeight(50),
                        child: HYContainer(
                          border:
                              Border(bottom: BorderSide(color: zs_color_f2)),
                          child: TabBar(
                            controller: tabController,
                            indicatorColor: ColorHex('#FF7D22'),
                            indicatorSize: TabBarIndicatorSize.label,
                            unselectedLabelColor: ColorHex('#999999'),
                            labelColor: ColorHex('#333333'),
                            indicatorPadding: const EdgeInsets.only(
                              left: 5,
                              right: 5,
                              bottom: 1,
                            ),
                            tabs: tabs
                                .map((TabbarItem e) => Tab(
                                      child: ZsText(
                                        e.title ?? '',
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ))
                                .toList(),
                          ),
                        ),
                      )
                    : null),
            body: TabBarView(
                controller: tabController,
                children: tabs.map((TabbarItem e) => e.page!).toList()),
          )),
      if (manager != null) manager!.build(context)
    ]);
  }

  @override
  bool get wantKeepAlive => true;

  ///立即打卡：1.定位取经纬度 2.接口请求获取地址 3.判断平台host并请求打卡接口
  clockIn() async {
    await logic.startLocation();
    EasyLoading.show();
    requestClockIn();
  }

  requestClockIn() {
    final DateTime dateTime = DateTime.now();
    String remark = '';
    if (dateTime.hour < 12) {
      remark = 'am';
    } else {
      remark = 'pm';
    }
    get(
        path: zsAttendClockIn,
        otherHost: ZsMemeryCache.zsWorkLoginModel?.workPath,
        queryParams: {
          'userId': ZsMemeryCache.zsWorkLoginModel?.workModuleUserId,
          'lat': logic.lat,
          'lon': logic.lng,
          'address': logic.address,
          'remark': remark

          ///此参数传什么内容无所谓，因为后台接口已自行判断
        }).then((value) {
      EasyLoading.dismiss();
      try {
        if (value!.resultCode == 0) {
          EasyLoading.showSuccess('打卡成功');
        } else {
          EasyLoading.showError(value.errMsg.toString());
        }
      } catch (e) {
        EasyLoading.dismiss();
        requestClockIn();
      }
    });
  }
}
